package com.fintech.third.utils.bairong;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;

import com.fintech.third.service.bairong.NullHostNameVerifier;

import okhttp3.MediaType;
import sun.net.www.protocol.https.Handler;

public class BaiRongUtil {
	private static final MediaType String = null;
	private static final String APPLICATION_JSON = "application/json";
	private static String[] hexDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e",
			"f" };

	
	/**
	 * 重写验证方法，取消检测ssl
	 */
	public static TrustManager truseAllManager = new X509TrustManager() {

		public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
				throws CertificateException {
			// TODO Auto-generated method stub

		}

		public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
				throws CertificateException {
			// TODO Auto-generated method stub

		}

		public java.security.cert.X509Certificate[] getAcceptedIssuers() {
			// TODO Auto-generated method stub
			return null;
		}

	};

	// 调用ssl
	private static void enableSSL(HttpClient httpClient) {
		try {
			SSLContext sslcontext = SSLContext.getInstance("TLS");
			sslcontext.init(null, new TrustManager[] { truseAllManager }, null);
			SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
			sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
			Scheme https = new Scheme("https", sf, 443);
			httpClient.getConnectionManager().getSchemeRegistry().register(https);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	
	/**
	 * 通过HttpsURLConnection发送请求
	 * 
	 * @param url
	 * @param post_str
	 * @return
	 */
	public static String urlConnectPost(String url, String post_str) {
		HttpsURLConnection urlCon = null;
		try {
			SSLContext sslcontext = SSLContext.getInstance("TLS");
			sslcontext.init(null, new TrustManager[] { truseAllManager }, null);
			urlCon.setDefaultSSLSocketFactory(sslcontext.getSocketFactory());
		} catch (KeyManagementException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		OutputStream out = null;
		BufferedReader in = null;
		StringBuffer sb = new StringBuffer();
		try {
			URL url1 = new URL(null, url, new Handler());
			urlCon = (HttpsURLConnection) url1.openConnection();
			urlCon.setConnectTimeout(30000);
			urlCon.setReadTimeout(30000);
			urlCon.setDoInput(true);
			urlCon.setDoOutput(true);
			urlCon.setRequestMethod("POST");
			urlCon.setRequestProperty("Content-Length", post_str.getBytes().length + "");
			urlCon.setUseCaches(false);
			urlCon.setDefaultHostnameVerifier(new NullHostNameVerifier());

			out = urlCon.getOutputStream();
			out.write(post_str.getBytes("UTF-8"));
			out.flush();
			urlCon.getOutputStream().close();
			in = new BufferedReader(new InputStreamReader(urlCon.getInputStream(), "utf-8"));
			String line;
			while ((line = in.readLine()) != null) {
				sb.append(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.close();
					if (in != null) {
						in.close();
					}
					if (urlCon != null) {
						urlCon.disconnect();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		}
		return sb.toString();
	}

	public static String getCheckData(String jsonData, String apiCode, String tokenId) {
		return genMd5(jsonData + genMd5(apiCode + tokenId));
	}

	public static String genMd5(String msg) {
		if(StringUtils.isBlank(msg)){
			return "";
		}
		String messageDigest = null;
		try {
			messageDigest = md5(msg);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("Md5 Error. Cause: " + e);
		}

		return messageDigest;
	}

	private static String md5(String data) throws NoSuchAlgorithmException, UnsupportedEncodingException {
		MessageDigest md5 = MessageDigest.getInstance("MD5");
		byte[] b = data.getBytes("UTF8");
		md5.update(b, 0, b.length);
		return byteArrayToHexString(md5.digest());
	}

	private static String byteArrayToHexString(byte[] b) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < b.length; i++) {
			sb.append(byteToHexString(b[i]));
		}
		return sb.toString();
	}

	private static String byteToHexString(byte b) {
		int n = b;
		if (n < 0)
			n += 256;
		int d1 = n / 16;
		int d2 = n % 16;
		return hexDigits[d1] + hexDigits[d2];
	}

}